package com.shujia.day12;

import java.util.*;

public class Code16MapDemo2 {
    public static void main(String[] args) {
        /*
            非常重要，背下来
            V get(Object key)
            Set<K> keySet()
            Collection<V> values()
            Set<Map.Entry<K,V>> entrySet()
         */

        HashMap<Animal, String> animalHashMap = new HashMap<>();

//        new Code16MapDemo2().new Animal(1,"花花"); 成员内部类的创建方式
        animalHashMap.put(new Code16MapDemo2.Animal(1,"花花"),"🐱");
        animalHashMap.put(new Code16MapDemo2.Animal(2,"毛栗"),"🐱");
        animalHashMap.put(new Code16MapDemo2.Animal(1,"花花"),"🐕");
        animalHashMap.put(new Code16MapDemo2.Animal(2,"旺旺"),"🐕");

        System.out.println(animalHashMap);
        // 对于添加的Animal其中两个对象的属性一样，应该要求只能保存一个

        String res = animalHashMap.get(new Animal(2, "旺旺"));
        System.out.println(res);

        Set<Animal> animalSet = animalHashMap.keySet();
        System.out.println(animalSet);


        Collection<String> values = animalHashMap.values();
        System.out.println(values);


        Set<Map.Entry<Animal, String>> entries = animalHashMap.entrySet();
        // entrySet是将HashMap中的所有元素（K-V）转换成一个Set集合，并且每一个K-V元素对应一个Entry

        for (Map.Entry<Animal, String> entry : entries) {
            Animal key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key:"+key+"\t"+"value:"+value);
        }

//        System.out.println(entries);
    }

    static class Animal{
        int age;
        String name;

        public Animal(int age, String name) {
            this.age = age;
            this.name = name;
        }

        public Animal() {
        }

        @Override
        public String toString() {
            return "Animal{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Animal animal = (Animal) o;
            return age == animal.age && Objects.equals(name, animal.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(age, name);
        }
    }
}

